#!/bin/bash

# 任务调度器部署脚本
# 适用于阿里云ECS

set -e

# 配置变量
IMAGE_NAME="task-scheduler"
CONTAINER_NAME="task-scheduler"
PORT="3001"
REGISTRY=""  # 如果有私有镜像仓库，在这里配置

echo "开始部署任务调度器..."

# 构建Docker镜像
echo "构建Docker镜像..."
docker build -t $IMAGE_NAME .

# 停止并删除旧容器（如果存在）
echo "停止旧容器..."
docker stop $CONTAINER_NAME 2>/dev/null || true
docker rm $CONTAINER_NAME 2>/dev/null || true

# 运行新容器
echo "启动新容器..."
docker run -d \
  --name $CONTAINER_NAME \
  --restart unless-stopped \
  -p $PORT:$PORT \
  -e TZ=Asia/Shanghai \
  $IMAGE_NAME

# 等待容器启动
echo "等待容器启动..."
sleep 10

# 检查容器状态
echo "检查容器状态..."
if docker ps | grep -q $CONTAINER_NAME; then
    echo "✅ 容器启动成功！"
    echo "📊 容器信息："
    docker ps | grep $CONTAINER_NAME
    echo ""
    echo "🌐 应用访问地址: http://localhost:$PORT"
    echo "📋 健康检查: http://localhost:$PORT/tasks"
else
    echo "❌ 容器启动失败！"
    echo "📋 查看容器日志："
    docker logs $CONTAINER_NAME
    exit 1
fi

echo "部署完成！"
